'use strict';

const heartbeats = require('heartbeats');
const EventEmitter = require('events');
const _ = require('lodash');

const packs = require('./pack');
const Protocol = require('./protocol');

module.exports = class Terminal extends EventEmitter {
  constructor(socket, app) {
    super();
    this.socket = socket;
    this.app = app;
    this.heart = heartbeats.createHeart(1000);
    this.heartPulse = this.heart.createPulse();

    this.socket.on('data', data => {
      this.handleData(data);
    });

    this.socket.on('close', () => {
      this.emit('leave');
    });

    this.socket.on('error', err => {
      this.emit('leave', err);
    });
  }

  handleData(data) {
    // test with telnet
    // console.log(data.toString('utf8'));
    // data = new Buffer(data.toString('utf8'), 'hex');

    console.log(data);
    if (data.length < 3) {
      return;
    }
    const dataHex = data.toString('hex').toUpperCase();
    const headHex = dataHex.substring(0, 6);

    console.log('head', headHex);
    if (headHex === '242424') {
      this.heartPulse.beat();
    } else if (headHex === '55AA01') {
      try {
        const protocol = Protocol.from(data);
        const Pack = packs[protocol.id];

        if (!Pack) {
          throw new Error('unkwon protocol id=' + protocol.id);
        }
        const pack = Pack.res(protocol);

        this.emit('data', pack);
        pack.handle(this.id, this.app);
      } catch (err) {
        this.app.logger.error(err.message);
        this.app.logger.error(data);
      }
    } else {
      const id = _.trim(Buffer.from(data).toString('utf8'));

      this.id = id;
      this.emit('ready', id);
    }
  }

  send(pack) {
    // this.socket.write(Protocol.fromRaw(pack).toBuffer(), () => {
    // });
  }

};
